package com.yupi.springbootinit.service.execution;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.enums.GenChartStrategyEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.GenChartStrategy;
import com.yupi.springbootinit.utils.ChartUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 同步生成
 * @TODO 反向压力
 **/
@Component(value = "gen_sync")
@Slf4j
//@Component(value = GenChartStrategyEnum.GEN_SYNC.getValue())
public class GenChartSync implements GenChartStrategy {

    @Resource
    ChartService chartService;

    @Resource
    AiManager aiManager;

    @Override
    public BiResponse executeGenChart(Chart chartEntity) {
        /* 较好的做法是在系统（模型）层面做预设效果一般来说，会比直接拼接在用户消息里效果更好一些。*/
        try{
            String userInput = ChartUtil.buildUserInput(chartEntity);
            // 调用AI，并获取返回值
            String result = aiManager.doChat(CommonConstant.BI_MODEL_ID, userInput);
            String[] split = result.split("【【【【【");
            // 第一个是 空字符串
            if (split.length != 3) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误!");
            }
            // 图表代码
            String genChart = split[1].trim();
            // 分析结果
            String genResult = split[2].trim();
            genChart = ChartUtil.compressJson(genChart);
            // 更新数据到数据库
            chartEntity.setStatus(FileConstant.SUCCEED);
            chartEntity.setGenResult(genResult);
            chartEntity.setGenChart(genChart);
            chartEntity.setStrategy(GenChartStrategyEnum.GEN_SYNC.getValue());
            boolean save = chartService.updateById(chartEntity);
            ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "图表保存失败!");
            // boolean syncResult = chartService.syncChart(chartEntity,genChart,genResult);
            // ThrowUtils.throwIf(!syncResult, ErrorCode.SYSTEM_ERROR, "图表同步失败!");
            // 记录生成日志
            // logService.recordLog(chartEntity);
            // 封装返回结果
            BiResponse biResponse = new BiResponse();
            biResponse.setGenChart(genChart);
            biResponse.setChartId(chartEntity.getId());
            biResponse.setGenResult(genResult);
            return biResponse;
        } catch (BusinessException e) {
            // 更新状态信息
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chartEntity.getId());
            updateChartResult.setStatus(FileConstant.FAILED);
            updateChartResult.setExecMessage("execMessage3");
            boolean updateResult = chartService.updateById(updateChartResult);
            // 记录生成日志
            // logService.recordLog(chartEntity);
            if (!updateResult) {
                log.info("更新图表FAILED状态信息失败 , chatId:{}", updateChartResult.getId());
            }
            // pointService.sendCompensateMessage(chartEntity.getUserId(), PointChangeEnum.GEN_CHART_FAILED_ADD);
            // 抛出异常进行日志打印
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }
}